// 获取地址详情
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { addressId } = event
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID

  if (!addressId) {
    return {
      success: false,
      message: '地址ID不能为空'
    }
  }

  try {
    // 查询地址详情
    const result = await db.collection('addresses')
      .doc(addressId)
      .get()

    if (!result.data) {
      return {
        success: false,
        message: '地址不存在'
      }
    }

    // 验证地址所有权
    if (result.data.userId !== userOpenid) {
      return {
        success: false,
        message: '无权访问该地址'
      }
    }

    return {
      success: true,
      data: result.data
    }
  } catch (error) {
    console.error('获取地址详情失败:', error)
    return {
      success: false,
      message: '获取地址详情失败',
      error: error.message
    }
  }
}